package o2o.web.actions.print;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ValidateUtil;
import net.sf.json.JSONObject;
import o2o.cache.print.PrintConfigMemory;
import o2o.cache.print.PrintMessageMemory;
import o2o.cache.sys.SysCustomerCache;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.order.ORDER_TYPE;
import o2o.dao.PO.order.OrderInfo;
import o2o.dao.PO.print.PRINT_TYPE;
import o2o.dao.PO.print.PrintConfig;
import o2o.dao.PO.print.PrintMessage;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.sys.SysCustomerInfo;
import o2o.dao.VO.order.OrderGoodsVO;
import o2o.dao.VO.order.OrderInfoVO;
import o2o.system.data.SYS_SETTINGS;
import o2o.web.actions.order.OrderMan;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import pay.weixin.utils.MD5Util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

public class PrintMan {

    public static final String FEI_E_URL = "http://api.feieyun.cn/Api/Open/";  // 飞鹅的url地址


    // 检测商户端是否已经注册了飞鹅账户
    public static boolean isAlreadyRegistered(String user, String uKey) {
        String result = send_fei_e_print_bind(user, uKey, "000#000"); // 输入一个假的值 会返回 信息  根据错误码不是-2（用户未注册）来显示
        if (ValidateUtil.isNull(result)) {
            return false;
        }
        JSONObject jsonObject = JSONObject.fromObject(result);
        if (jsonObject.containsKey("ret") && !jsonObject.getString("ret").equals("-2")) {
            return true;
        }
        return false;
    }


    // 获取店铺是否有指定标号的打印机
    public static PrintMessage getByMachine_code(Long shopId, Integer type, String machine_code) {
        if (ValidateUtil.isNotID(shopId) || ValidateUtil.isNull(machine_code)) {
            return null;
        }
        List<PrintMessage> list = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, type);
        if (ValidateUtil.isAbsList(list)) {
            for (PrintMessage p : list) {
                if (p == null) {
                    continue;
                }
                if (ValidateUtil.isNull(p.getMachine_code())) {
                    continue;
                }
                if (p.getMachine_code().equals(machine_code)) {
                    return p;
                }
            }
        }
        return null;
    }

    // 获取店铺打印机的配置信息 没有则会获取默认的
    public static PrintConfig getPrintConfigByShopId(Long shopId) {
        if (ValidateUtil.isNotID(shopId)) {
            return PrintConfigMemory.getInstance().getDefaultPrintConfig();
        }
        PrintConfig info = PrintConfigMemory.getInstance().getPrintConfigByShopId(shopId);
        if (info == null) {
            info = PrintConfigMemory.getInstance().getDefaultPrintConfig();
        }
        return info;
    }

    // 获取易云联打印机的配置信息
    public static PrintConfig getEYLPrintByShopId(Long shopId) {
        PrintConfig configByShopId = getPrintConfigByShopId(shopId);
        if (configByShopId == null) {
            return null;
        }
        // 根据用户id判断 若没有则取默认的
        if (ValidateUtil.isNull(configByShopId.getPartner())) {
            configByShopId = PrintConfigMemory.getInstance().getDefaultPrintConfig();
        }
        if (ValidateUtil.isNull(configByShopId.getPartner())) {
            return null;
        }
        return configByShopId;
    }


    // 飞鹅打印机绑定
    public static String add_fei_e_print(ShopInfo shopInfo, Long shopId, String machine_code, String name, String mkey, Integer pTime, String createUser) {
        // 获取店铺的配置信息
        PrintConfig infoConfig = PrintMan.getPrintConfigByShopId(shopId);
        if (infoConfig == null) {
            return AjaxResult.errorResult("未获取到配置信息");
        }
        String result = PrintMan.send_fei_e_print_bind(infoConfig.getFeUser(), infoConfig.getFeUKey(), machine_code + "#" + mkey);
        if (ValidateUtil.isNull(result)) {
            return AjaxResult.errorResult("添加失败，请稍后重试");
        }
        JSONObject jsonObject = JSONObject.fromObject(result);

        /*处理多用户 ----start----*/
//        if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
//            JSONObject json = JSONObject.fromObject(jsonObject.getString("data"));
//            String no = json.getString("no");
//            if (no!=null&&no.indexOf("已被添加过") != -1) {
//                //如果官网返回存在结果,查询本地记录，如果存在返回绑定成功，如果不存在，插入本地记录
////            PrintMessage printMessage = null;
////            StringBuffer sb = new StringBuffer();
////            /*SELECT partner,apikey,username,mobilephone FROM print_message WHERE id=1*/
//////            sb.append("SELECT partner,apikey,mkey,username,mobilephone FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE machine_code=")
//////                    .append("\'").append(machine_code).append("\' AND delflag=0");
////            sb.append("SELECT partner,apikey,mkey,username,mobilephone FROM ").append(PojoTables.PRINT_MESSAGE).append(" WHERE shopId=")
////                    .append(shopId).append(" AND delflag=0");
////
////
////            try {
////                printMessage = (PrintMessage) UserDaoSql.getInstance().getObject(PrintMessage.class, sb.toString());
////            } catch (SQLException e) {
////                e.printStackTrace();
////            }
////            if (printMessage == null) {
//                if (!machine_codeInShop(shopId, machine_code)) {
//                    // 本地数据插
//                 return insertshop(shopInfo,shopId,machine_code,name,mkey,pTime,createUser,infoConfig);
//                }
//
//            }
//        } else {
//
//            if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
//                JSONObject json = JSONObject.fromObject(jsonObject.getString("data"));
//                String no = json.getString("no");
//                if (ValidateUtil.isNull(no) || ValidateUtil.isNull(no.trim()) || no.trim().equals("[]")) {
//
//                } else {
//                    return AjaxResult.errorResult(no.replace("]", "").replace("[", "").replaceAll("\"", ""));
//                }
//            } else if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("-2")) {
//                return AjaxResult.errorResult("参数错误 : 该帐号未注册.");
//            } else {
//                return AjaxResult.errorResult("添加失败，请稍后重试");
//            }
//            if (ValidateUtil.isNotAbsInteger(pTime)) {
//                pTime = 1;
//            }
//            return insertshop(shopInfo,shopId,machine_code,name,mkey,pTime,createUser,infoConfig);
//
//        }

        if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
            JSONObject json = JSONObject.fromObject(jsonObject.getString("data"));
            String no = json.getString("no");
            if (no != null && no.indexOf("已被添加过") != -1) {
                if (!machine_codeInShop(shopId, machine_code)) {
                    // 本地数据插
                    return insertshop(shopInfo, shopId, machine_code, name, mkey, pTime, createUser, infoConfig);
                } else if (machine_codeInShop(shopId, machine_code)) {
                    return AjaxResult.errorResult("添加失败,重复添加");
                }
            } else {
                return AjaxResult.errorResult(no.replace("]", "").replace("[", "").replaceAll("\"", ""));
            }
        } else if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("-2")) {
            return AjaxResult.errorResult("参数错误 : 该帐号未注册.");
        } else {
            return AjaxResult.errorResult("添加失败，请稍后重试");
        }
        if (ValidateUtil.isNotAbsInteger(pTime)) {
            pTime = 1;
        }
        return insertshop(shopInfo, shopId, machine_code, name, mkey, pTime, createUser, infoConfig);
        /*----end-----*/


    }

    // 添加飞鹅打印机
    private static String send_fei_e_print_bind(String user, String uKey, String snList) {
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();
        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();
        HttpPost post = new HttpPost(FEI_E_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", user));
        String STIME = String.valueOf(DateUtils.getCurrTime() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(user, uKey, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printerAddlist"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("printerContent", snList));
        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 添加易云联终端
    public static String add_e_yunlian_print(ShopInfo shopInfo, Long shopId, String machine_code, String name, String mkey, Integer pTime, String createUser, String mobilePhone, PrintConfig config) {
        if (config == null) {
            return AjaxResult.errorResult("未获取到易联云配置信息");
        }
        String resultCode = send_e_yunlian_print_bind(config.getEyUsername(), mobilePhone, ValidateUtil.isNull(name) ? shopInfo.getShopName() : name, machine_code, config.getApiKey(), mkey, config.getPartner());
        if ("2".equals(resultCode)) {
            //  易联云已经绑定了，但是库里没有更新
        } else if ("3".equals(resultCode) || "4".equals(resultCode)) {
            return AjaxResult.errorResult("服务器异常，稍后再试");
        } else if ("5".equals(resultCode)) {
            return AjaxResult.errorResult("用户验证失败");
        } else if ("6".equals(resultCode)) {
            return AjaxResult.errorResult("终端号非法");
        } else {
            return AjaxResult.errorResult("绑定失败");
        }

        if ("1".equals(resultCode) || "2".equals(resultCode)) {
            // 已经插入成功了
            // 首先查询
            List<PrintMessage> printMessageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, PRINT_TYPE.PRINT_TYPE_EYUNLIAN);
            boolean isExist = false;
            if (ValidateUtil.isAbsList(printMessageList)) {
                for (PrintMessage p : printMessageList) {
                    if (p == null) {
                        continue;
                    }
                    if (ValidateUtil.isNotNull(p.getMachine_code()) && p.getMachine_code().equals(machine_code)) {
                        isExist = true;
                        break;
                    }
                }
            }
            // 是否添加
            if (!isExist) {
                long time = DateUtils.getCurrTime();// 创建时间
                PrintMessage p = new PrintMessage();
                p.setName(ValidateUtil.isNull(name) ? shopInfo.getShopName() : name).setMachine_code(machine_code).setShopId(shopId).setCreateUser(createUser)
                        .setCreateTime(time).setApikey(config.getApiKey()).setPartner(config.getPartner()).setDelFlag(0)
                        .setFeTime(pTime).setMkey(mkey).setUsername(config.getEyUsername()).setMobilePhone(mobilePhone).setId(null);
                try {
                    UserDaoSql.getInstance().insertObj(PojoTables.PRINT_MESSAGE, p);
                } catch (Exception e) {
                    e.printStackTrace();
                    // 删除远程终端
                    send_e_yunlian_print_unbind(config.getPartner(), machine_code, config.getApiKey(), mkey);
                    return AjaxResult.errorResult(e.getMessage());
                }
                // 缓存
                PrintMessageMemory.getInstance().add(time);
            }
            return AjaxResult.successResult("绑定成功");
        }
        return AjaxResult.successResult("绑定成功");
    }

    // 添加易联云打印机
    private static String send_e_yunlian_print_bind(String username, String mobilePhone, String name, String machine_code, String apiKey, String mKey, String partner) {
        //  发送绑定打印机的请求
        Map<String, String> params = new HashMap<>();
        params.put("partner", partner);                 //  用户id
        params.put("machine_code", machine_code);       //  打印机终端号
        params.put("username", username);               //   管理中心的用户名（非商户的用户名）
        params.put("printname", name);                        // 打印机名称（以商户名）
        if (ValidateUtil.isNotNull(mobilePhone)) {
            params.put("mobilephone", mobilePhone);                  // 空值
        }
        String sign = PrintMan.signRequest(params, apiKey, mKey);
        params.put("msign", mKey);                      //  打印机终端密钥
        params.put("sign", sign);

        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("http://open.10ss.net:8888/addprint.php");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            post.addParameter(entry.getKey(), entry.getValue());
        }
        HttpMethodParams param = post.getParams();
        param.setContentCharset("UTF-8");
        try {
            httpClient.executeMethod(post);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //如果返回200，表明成功
        String result = "";
        try {
            result = post.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }


    // 解绑飞鹅打印机
    public static String del_print_fei_e_unbind(PrintMessage printMessageDB) {
        // 删除
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库异常");
        }
        Long count = 0L;
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.PRINT_MESSAGE).append(" set ")
                .append(" delFlag =1 ").append(" where id =").append(printMessageDB.getId());
        StringBuffer getSql = new StringBuffer();
        getSql.append("select count(*) as counts from ").append(PojoTables.PRINT_MESSAGE).append(" where id !=").append(printMessageDB.getId())
                .append(" and machine_code=").append(printMessageDB.getMachine_code()).append(" and delFlag = 0");
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
            count = UserDaoSql.getInstance().getCount(getSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("删除失败，请稍重试");
        }
        if (count.longValue() == 0) {
            String result = PrintMan.send_fei_e_print_unbind(printMessageDB.getFeUser(), printMessageDB.getFeUkey(), printMessageDB.getMachine_code());
            if (ValidateUtil.isNull(result)) {
                return AjaxResult.errorResult("添加失败，请稍后重试");
            }
            JSONObject jsonObject = JSONObject.fromObject(result);
            if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
                JSONObject json = JSONObject.fromObject(jsonObject.getString("data"));
                String no = json.getString("no");
                if (ValidateUtil.isNull(no) || ValidateUtil.isNull(no.trim()) || no.trim().equals("[]")) {

                } else {
                    UserDaoSql.getInstance().rollback(conn);
                    return AjaxResult.errorResult(no.replace("]", "").replace("[", ""));
                }
            } else if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("-2")) {
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
                return AjaxResult.errorResult("参数错误 : 该帐号未注册.");
            } else {
                UserDaoSql.getInstance().rollback(conn);
                UserDaoSql.getInstance().close(conn);
                return AjaxResult.errorResult("远程删除失败，请稍后重试");
            }
        }
//        String result = PrintMan.send_fei_e_print_unbind(printMessageDB.getFeUser(), printMessageDB.getFeUkey(), printMessageDB.getMachine_code());
//        if (ValidateUtil.isNull(result)) {
//            return AjaxResult.errorResult("添加失败，请稍后重试");
//        }
//        JSONObject jsonObject = JSONObject.fromObject(result);
//        if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
//            JSONObject json = JSONObject.fromObject(jsonObject.getString("data"));
//            String no = json.getString("no");
//            if (ValidateUtil.isNull(no) || ValidateUtil.isNull(no.trim()) || no.trim().equals("[]")) {
//
//            } else {
//                UserDaoSql.getInstance().rollback(conn);
//                return AjaxResult.errorResult(no.replace("]", "").replace("[", ""));
//            }
//        } else if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("-2")) {
//            UserDaoSql.getInstance().rollback(conn);
//            return AjaxResult.errorResult("参数错误 : 该帐号未注册.");
//        } else {
//            UserDaoSql.getInstance().rollback(conn);
//            return AjaxResult.errorResult("远程删除失败，请稍后重试");
//        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            return AjaxResult.errorResult("数据库执行书屋失败");
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 更新缓存
        PrintMessageMemory.getInstance().del(printMessageDB.getId());

        return AjaxResult.successResult();
    }

    // 解绑易联云打印机
    public static String del_print_e_yunlian_unbind(PrintMessage printMessageDB) {
        Connection conn = null;
        try {
            conn = UserDaoSql.getInstance().getConnection();
            conn.setAutoCommit(false);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.errorResult("数据库异常");
        }
        StringBuffer sql = new StringBuffer();
        sql.append("update ").append(PojoTables.PRINT_MESSAGE).append(" set ")
                .append(" delFlag =1 ").append(" where id =").append(printMessageDB.getId());
        try {
            UserDaoSql.getInstance().executeBySql(sql.toString(), conn);
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            UserDaoSql.getInstance().close(conn);
            return AjaxResult.errorResult("删除失败，请稍重试");
        }
        //是不是需要解绑官网上的打印机设备
        StringBuffer selectSql = new StringBuffer();
        selectSql.append("select count(*) as counts from ").append(PojoTables.PRINT_MESSAGE).append(" where delFlag =0 and id!= ").append(printMessageDB.getId())
                .append(" and machine_code=").append(printMessageDB.getMachine_code()).append(" and type=").append(printMessageDB.getType());
        Long counts = null;
        try {
            counts = UserDaoSql.getInstance().getCount(selectSql.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 数据库中没有了 那么直接删除删除官网的
        if (counts == null || counts.longValue() == 0) {
            String result = PrintMan.send_e_yunlian_print_unbind(printMessageDB.getPartner(), printMessageDB.getMachine_code(), printMessageDB.getApikey(), printMessageDB.getMkey());
        }
        try {
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            UserDaoSql.getInstance().rollback(conn);
            return AjaxResult.errorResult("数据库执行书屋失败");
        } finally {
            UserDaoSql.getInstance().close(conn);
        }
        // 更新缓存
        PrintMessageMemory.getInstance().del(printMessageDB.getId());
        return AjaxResult.successResult();
    }

    // 解绑 飞鹅
    private static String send_fei_e_print_unbind(String user, String uKey, String snList) {
        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(FEI_E_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", user));
        String STIME = String.valueOf(DateUtils.getCurrTime() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(user, uKey, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printerDelList"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("snlist", snList));
        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 解绑 易联云
    private static String send_e_yunlian_print_unbind(String partner, String machine_code, String apiKey, String mKey) {
        Map<String, String> params = new HashMap<>();
        params.put("partner", partner);                 //  用户id
        params.put("machine_code", machine_code);       //  打印机终端号

        String sign = signRequest(params, apiKey, mKey);

        // params.put("msign", mKey);                      //  打印机终端密钥
        params.put("sign", sign);

        HttpClient httpClient = new HttpClient();
        PostMethod post = new PostMethod("http://open.10ss.net:8888/removeprint.php");

        for (Map.Entry<String, String> entry : params.entrySet()) {
            post.addParameter(entry.getKey(), entry.getValue());
        }


        HttpMethodParams param = post.getParams();
        param.setContentCharset("UTF-8");
        try {
            httpClient.executeMethod(post);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        //如果返回200，表明成功
        String result = "";
        try {
            result = post.getResponseBodyAsString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 打印
    private static String fe_print(String user, String uKey, String content, String sn, int time) {
        //标签说明：
        //单标签:
        //"<BR>"为换行,"<CUT>"为切刀指令(主动切纸,仅限切刀打印机使用才有效果)
        //"<LOGO>"为打印LOGO指令(前提是预先在机器内置LOGO图片),"<PLUGIN>"为钱箱或者外置音响指令
        //成对标签：
        //"<CB></CB>"为居中放大一倍,"<B></B>"为放大一倍,"<C></C>"为居中,<L></L>字体变高一倍
        //<W></W>字体变宽一倍,"<QR></QR>"为二维码,"<BOLD></BOLD>"为字体加粗,"<RIGHT></RIGHT>"为右对齐
        //拼凑订单内容时可参考如下格式
        //根据打印纸张的宽度，自行调整内容的格式，可参考下面的样例格式

//        String content;
//        content = "<CB>测试打印</CB><BR>";
//        content += "名称　　　　　 单价  数量 金额<BR>";
//        content += "--------------------------------<BR>";
//        content += "饭　　　　　　 1.0    1   1.0<BR>";
//        content += "炒饭　　　　　 10.0   10  10.0<BR>";
//        content += "蛋炒饭　　　　 10.0   10  100.0<BR>";
//        content += "鸡蛋炒饭　　　 100.0  1   100.0<BR>";
//        content += "番茄蛋炒饭　　 1000.0 1   100.0<BR>";
//        content += "西红柿蛋炒饭　 1000.0 1   100.0<BR>";
//        content += "西红柿鸡蛋炒饭 100.0  10  100.0<BR>";
//        content += "备注：加辣<BR>";
//        content += "--------------------------------<BR>";
//        content += "合计：xx.0元<BR>";
//        content += "送货地点：广州市南沙区xx路xx号<BR>";
//        content += "联系电话：13888888888888<BR>";
//        content += "订餐时间：2016-08-08 08:08:08<BR>";
//        content += "<QR>http://www.dzist.com</QR>";

        //通过POST请求，发送打印信息到服务器
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(30000)//读取超时
                .setConnectTimeout(30000)//连接超时
                .build();

        CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build();

        HttpPost post = new HttpPost(FEI_E_URL);
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("user", user));
        String STIME = String.valueOf(System.currentTimeMillis() / 1000);
        nvps.add(new BasicNameValuePair("stime", STIME));
        nvps.add(new BasicNameValuePair("sig", signature(user, uKey, STIME)));
        nvps.add(new BasicNameValuePair("apiname", "Open_printMsg"));//固定值,不需要修改
        nvps.add(new BasicNameValuePair("sn", sn));
        nvps.add(new BasicNameValuePair("content", content));
        nvps.add(new BasicNameValuePair("times", time + ""));//打印联数

        CloseableHttpResponse response = null;
        String result = null;
        try {
            post.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            response = httpClient.execute(post);
            int statecode = response.getStatusLine().getStatusCode();
            if (statecode == 200) {
                HttpEntity httpentity = response.getEntity();
                if (httpentity != null) {
                    //服务器返回的JSON字符串，建议要当做日志记录起来
                    result = EntityUtils.toString(httpentity);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                post.abort();
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    // 打印
    public static boolean sendFeContent(String content, String user, String uKey, String sn, Integer time) {
        if (ValidateUtil.isNotAbsInteger(time)) {
            time = 1;
        }
        String res = fe_print(user, uKey, content, sn, time);
        if (res == null) {
            return false;
        }
        JSONObject jsonObject = JSONObject.fromObject(res);
        if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
            return true;
        } else if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("-2")) {
            System.out.println("参数错误 : 该帐号未注册");
            return false;
        }
        return false;
    }

    private static boolean sendEYunLianContent(String content, String partner, String machine_code, String apiKey, String mkey) {
        System.out.println("content====" + content);
        try {
            Map<String, String> params = new HashMap<String, String>();
            params.put("partner", partner);
            params.put("machine_code", machine_code);
            String time = String.valueOf(System.currentTimeMillis());
            params.put("time", time);
            String sign = signRequest(params, apiKey, mkey);

            byte[] data = ("partner=" + partner + "&machine_code=" + machine_code + "&content=" + content + "&sign=" + sign + "&time=" + time).getBytes();

            URL url = new URL("http://open.10ss.net:8888");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(5 * 1000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/html; charset=utf-8");
            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            //获取输出流
            OutputStream outStream = conn.getOutputStream();
            //传入参数
            outStream.write(data);
            outStream.flush();
            outStream.close();
            //获取输入流
            InputStream is = conn.getInputStream();
            System.out.println(conn.getResponseCode());
            if (conn.getResponseCode() == 200) {
                int i = -1;
                byte[] b = new byte[1024];
                StringBuffer result = new StringBuffer();
                while ((i = is.read(b)) != -1) {
                    result.append(new String(b, 0, i));
                }
                String sub = result.toString();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 飞鹅打印信息
    public static String get_F_E_Content(OrderInfoVO infoVO, String customerName, boolean sureBySystem) throws Exception {
        String content = "";
        if (SYS_SETTINGS.PRINT_STYLE_TYPE != null && SYS_SETTINGS.PRINT_STYLE_TYPE == 2) {
            // 美团的
            content = get_F_E_Content_MT(infoVO, customerName);
        } else {
            // 本系统的
            content = get_F_E_Content_XT(infoVO, customerName);
        }
        //p0'g
        if (sureBySystem && ValidateUtil.isNotNull(content) && ValidateUtil.isNotNull(SYS_SETTINGS.PRINT_NEW_ORDER_INSTRUCTION)) {
            content += SYS_SETTINGS.PRINT_NEW_ORDER_INSTRUCTION;
        }
        return content;
    }

    // 飞鹅打印信息 系统
    public static String get_F_E_Content_XT(OrderInfoVO infoVO, String customerName) {
        if (infoVO == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (ValidateUtil.isNotNull(SYS_SETTINGS.LOCAL_PROJECT_TIME_ZONE)) {
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone(SYS_SETTINGS.LOCAL_PROJECT_TIME_ZONE));
        }
        StringBuffer sb = new StringBuffer();
        sb.append("<CB>" + customerName + "</CB>").append("<BR>");
        sb.append("<B>").append(infoVO.getPreDayNo()).append("</B>").append("<BR>").append("<BR>");
        if (infoVO.getIsAppointment() != null && infoVO.getIsAppointment() == 1) {
            sb.append("<CB>").append("预约单").append("</CB>").append("<BR>");
        }
        sb.append("店    铺:").append(infoVO.getShopName()).append("<BR>");   // 打印多联
        sb.append("姓    名:").append(infoVO.getBuyer()).append("<BR>");   // 姓名
        sb.append("联系方式:").append("<W>").append(infoVO.getTelephone()).append("</W>").append("<BR>");   // 联系方式
        sb.append("订单时间:").append(simpleDateFormat.format(infoVO.getCreateTime())).append("<BR>");   // 订单时间
//        if (infoVO.getIsAppointment() != null && infoVO.getIsAppointment() == 1) {
// if (ValidateUtil.isNull(infoVO.getZiQuTime()) || ValidateUtil.isNotAbsLong(infoVO.getZiQuTime())) {
//        sb.append("<C><B>" + "按指定时间送达：" + "立即送达" + "</B></C>" + "<BR>");
//    } else {
//        sb.append("<C><B>" + "按指定时间送达：" + simpleDateFormat.format(infoVO.getZiQuTime()) + "<C><B>" + "<BR>");
//    }
//        }
        if (ValidateUtil.isNull(infoVO.getZiQuTime()) || ValidateUtil.isNotAbsLong(infoVO.getZiQuTime())) {
            sb.append("按指定时间送达：" + "<W>" + "立即送达" + "</W>" + "<BR>");
        } else {
            sb.append("按指定时间送达：" + "<BR><W>" + simpleDateFormat.format(infoVO.getZiQuTime()) + "</W>" + "<BR>");
        }
        sb.append("订单编号:").append(infoVO.getOrderNo()).append("<BR>").append("<BR>");   // 订单编号
        if (SYS_SETTINGS.HAS_ORDER_SECOND_POSTMAN_VERIFY_CODE == 1 && ValidateUtil.isNotNull(infoVO.getVerifyCode())) {
            sb.append("提货码:").append(infoVO.getVerifyCode()).append("<BR>");
        }
        List<OrderGoodsVO> goodsVOList = infoVO.getGoods();
        String symbol = "￥";
        if (SYS_SETTINGS.USE_MAIN_CURRENCY_PAY != null && SYS_SETTINGS.USE_MAIN_CURRENCY_PAY != 1) {
            symbol = ValidateUtil.isNull(SYS_SETTINGS.CURRENCY_UNIT) ? "" : SYS_SETTINGS.CURRENCY_UNIT;
        }
        // 订单商品
        if (ValidateUtil.isAbsList(goodsVOList)) {
            sb.append("---------商品清单-----------<BR>");
            for (OrderGoodsVO g : goodsVOList) {
                // 规格
                String specs = "";
                if (StringUtils.isNotEmpty(g.getSpecs()) && !"null".equalsIgnoreCase(g.getSpecs())) {
                    specs = " " + g.getSpecs();
                }
                // 属性
                String goodsAttrVals = "";
                if (StringUtils.isNotEmpty(g.getGoodsAttrVals()) && !"null".equalsIgnoreCase(g.getGoodsAttrVals())) {
                    goodsAttrVals = "  属性:" + g.getGoodsAttrVals();
                }
                if (g.getIsZhekou() == null || g.getIsZhekou() == 0) {
                    sb.append("<L>").append(g.getName()).append(specs).append("  ").append(symbol).append(g.getGoodsPrice()).append(" ").append(" <B>*").append(g.getTotalCount()).append("<B>").append(ValidateUtil.isNull(g.getGoodsAttrVals()) ? "" : g.getGoodsAttrVals()).append("</L>").append("<BR>");
                } else {
                    sb.append("<L>").append(g.getName()).append(specs).append("(折)").append("  ").append(symbol).append(g.getGoodsPrice()).append(" ").append(" <B>*").append(g.getTotalCount()).append("<B>").append(ValidateUtil.isNull(g.getGoodsAttrVals()) ? "" : g.getGoodsAttrVals()).append("</L>").append("<BR>");
                }
                if (StringUtils.isNotEmpty(goodsAttrVals)) {
                    sb.append("<L>").append(goodsAttrVals).append("</L>").append("<BR>");
                }
            }
        }
        sb.append("<BR>");
        sb.append("<BR>");
        // 活动信息
        if (infoVO.getGameAward() != null && infoVO.getGameAward().size() > 0) {
            sb.append("-------优惠信息-----<BR>");
            if (infoVO.getGameAward().size() == 1) {
                sb.append(("优    惠：" + infoVO.getGameAward().get(0).getAward() + "\n"));
            } else {
                for (int i = 0; i < infoVO.getGameAward().size(); i++) {
                    sb.append(("优    惠：" + (i + 1) + infoVO.getGameAward().get(i).getAward() + "\n"));
                }
            }
        }
        // 打包费
        if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
            String canju = "";//餐具
            String dabaofei = "";//打包费
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                if (null != infoVO.getCanJuPrice() && infoVO.getCanJuPrice() > 0) {
                    canju = "餐具：" + infoVO.getCanJuPrice() + "  x" + infoVO.getCanJuCount();
                } else {
                    canju = "餐具：" + "  x" + infoVO.getCanJuCount();
                }
            }
            if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
                dabaofei = "打包费：" + infoVO.getPacketPrice();
            }
            sb.append(canju).append("<BR>");
            sb.append(dabaofei).append("<BR>");
        } else {
            String canju = "";//餐具
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                if (null != infoVO.getCanJuPrice() && infoVO.getCanJuPrice() > 0) {
                    canju = "餐具：" + infoVO.getCanJuPrice() + "  x" + infoVO.getCanJuCount();
                } else {
                    canju = "餐具：" + "  x" + infoVO.getCanJuCount();
                }
            }
            sb.append(canju);
        }
        if (infoVO.getIsZiQu() != 1) {
            sb.append("运    费:").append(infoVO.getDeliveryPrice()).append("<BR>");
        }
        sb.append("优惠金额:").append(infoVO.getAwardMoney()).append("<BR>");
        sb.append("总计金额:").append(infoVO.getTotalPrice()).append("<BR>");
        sb.append("支付金额:").append(infoVO.getTotalPrice()).append("<BR>");
        if (ValidateUtil.isNotNull(infoVO.getPayType())) {
            if (infoVO.getPayType().contains("wx")) {
                sb.append("支付方式:").append("微信").append("<BR>");
            } else if (infoVO.getPayType().contains("alipay")) {
                sb.append("支付方式:").append("支付宝").append("<BR>");
            }
        }
        if (infoVO.getIsZiQu() == 1) {
            // 自取
            sb.append("方    式:").append("自    提").append("<BR>");
        } else {
            //配送
            sb.append("方    式:").append("配    送").append("<BR>");
            String address = "";
            if (SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY != null && SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY == 1) {
                if (ValidateUtil.isNotNull(infoVO.getProvince())) {
                    address += " " + infoVO.getProvince();
                }
                if (ValidateUtil.isNotNull(infoVO.getCity())) {
                    address += " " + infoVO.getCity();
                }
                if (ValidateUtil.isNotNull(infoVO.getCounty())) {
                    address += " " + infoVO.getCounty();
                }
                address += "" + infoVO.getAddress();
            } else if (SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY != null && SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY == 2) {
                address += "" + infoVO.getAddress();
                if (ValidateUtil.isNotNull(infoVO.getCounty())) {
                    address += " " + infoVO.getCounty();
                }
                if (ValidateUtil.isNotNull(infoVO.getCity())) {
                    address += " " + infoVO.getCity();
                }
                if (ValidateUtil.isNotNull(infoVO.getProvince())) {
                    address += " " + infoVO.getProvince();
                }
            } else {
                address += "" + infoVO.getAddress();
            }
//            sb.append("地    址:").append("<W>").append(infoVO.getAddress()).append("</W>").append("<BR>");
            sb.append("地    址:").append("<W>").append(address).append("</W>").append("<BR>");
        }
        sb.append("备    注:").append("<BR><W>").append(ValidateUtil.isNull(infoVO.getNote()) ? "" : infoVO.getNote()).append("</W>").append("<BR>").append("<BR>");
        if (SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE != null && SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE == 1 && ValidateUtil.isNotNull(infoVO.getShopNote())) {
            sb.append("商家 备注:").append("<BR><W>").append(ValidateUtil.isNull(infoVO.getShopNote()) ? "" : infoVO.getShopNote()).append("</W>").append("<BR>").append("<BR>");
        }
        if (SYS_SETTINGS.IS_PRINT_QR_CODE != null && SYS_SETTINGS.IS_PRINT_QR_CODE == 1) {
            sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        }
//        sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        return sb.toString();
    }

    // 飞鹅打印信息 美团
    public static String get_F_E_Content_MT(OrderInfoVO infoVO, String customerName) throws Exception {
        if (infoVO == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        if (ValidateUtil.isNotNull(SYS_SETTINGS.LOCAL_PROJECT_TIME_ZONE)) {
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone(SYS_SETTINGS.LOCAL_PROJECT_TIME_ZONE));
        }
        StringBuilder sb = new StringBuilder();

        sb.append("<CB>" + customerName + "</CB>").append("<BR>");
        sb.append("<C>*****  <BOLD><L># " + infoVO.getPreDayNo() + "</L></BOLD>  *****</C>").append("<BR>");
        sb.append("<CB>" + infoVO.getShopName() + "</CB>").append("<BR>");
        if (infoVO.getIsAppointment() != null && infoVO.getIsAppointment() == 1) {
            sb.append("<CB>").append("预约单").append("</CB>").append("<BR>");
        }
        sb.append("下单时间: " + simpleDateFormat.format(infoVO.getCreateTime())).append("<BR>");
        sb.append("--------------------------------").append("<BR>");
        sb.append("<B>备注:" + ((StringUtils.isEmpty(infoVO.getNote()) || infoVO.getNote().equalsIgnoreCase("null")) ? "" : infoVO.getNote()) + "</B>");
        sb.append("<BR>");
        if (SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE != null && SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE == 1 && ValidateUtil.isNotNull(infoVO.getShopNote())) {
            sb.append("<B>商家备注:" + ((StringUtils.isEmpty(infoVO.getShopNote()) || infoVO.getShopNote().equalsIgnoreCase("null")) ? "" : infoVO.getShopNote()) + "</B>");
            sb.append("<BR>");
        }
        sb.append("<C>-------- 商 品 清 单 --------</C>").append("<BR>");
        List<OrderGoodsVO> goodsVOList = infoVO.getGoods();
        if (goodsVOList != null && !goodsVOList.isEmpty()) {
            for (OrderGoodsVO tempInfo : goodsVOList) {
                String tempStr = getGoodsRow_FE(tempInfo);
                if (StringUtils.isNotEmpty(tempStr)) {
                    sb.append("<L>").append(tempStr).append("</L>");
                    sb.append("<BR>");
                }
            }
        }
        sb.append("<BR>");
        sb.append("<C>------- 其 他 信 息 -------</C>").append("<BR>");
        sb.append("订单编号:").append(infoVO.getOrderNo()).append("<BR>");
        if (SYS_SETTINGS.HAS_ORDER_SECOND_POSTMAN_VERIFY_CODE == 1 && ValidateUtil.isNotNull(infoVO.getVerifyCode())) {
            sb.append("提货码:").append(infoVO.getVerifyCode()).append("<BR>");
        }
        sb.append("商家电话:").append(infoVO.getShopPhone()).append("<BR>");
        if (ValidateUtil.isNull(infoVO.getZiQuTime()) || ValidateUtil.isNotAbsLong(infoVO.getZiQuTime())) {
            sb.append("送达时间:").append("<BOLD>").append("立即送达").append("</BOLD>").append("<BR>");
        } else {
            sb.append("送达时间:").append("<BOLD>").append(simpleDateFormat.format(infoVO.getZiQuTime())).append("</BOLD>").append("<BR>");
        }

        if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                String temp = getOtherRow("餐具", infoVO.getCanJuPrice() == null ? null : infoVO.getCanJuPrice() + "", infoVO.getCanJuCount() + "", "");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
            if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
                String temp = getOtherRow("打 包 费", null, infoVO.getPacketPrice() + "", "￥");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
        } else {
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                String temp = getOtherRow("餐具", infoVO.getCanJuPrice() == null ? null : infoVO.getCanJuPrice() + "", infoVO.getCanJuCount() + "", "");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
        }
        String temp = "";
        // 运费
        if (infoVO.getIsZiQu() != 1) {
            temp = getOtherRow("运    费", null, infoVO.getDeliveryPrice() + "", null);
            if (StringUtils.isNotEmpty(temp)) {
                sb.append(temp);
            }
        }
        temp = getOtherRow("优惠金额", null, infoVO.getAwardMoney() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
        temp = getOtherRow("总计金额", null, infoVO.getTotalMoney() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
        temp = getOtherRow("支付金额", null, infoVO.getTotalPrice() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
        sb.append("--------------------------------").append("<BR>");

        if (infoVO.getIsZiQu() == 1) {
            // 自取
            sb.append("方    式:<BOLD>").append("<L>自    提</L>").append("</BOLD><BR>");
        } else {
            //配送
            sb.append("方    式:").append("<BOLD><L>配    送</L></BOLD>").append("<BR>");
            String address = "";
            if (SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY != null && SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY == 1) {
                if (ValidateUtil.isNotNull(infoVO.getProvince())) {
                    address += " " + infoVO.getProvince();
                }
                if (ValidateUtil.isNotNull(infoVO.getCity())) {
                    address += " " + infoVO.getCity();
                }
                if (ValidateUtil.isNotNull(infoVO.getCounty())) {
                    address += " " + infoVO.getCounty();
                }
                address += "" + infoVO.getAddress();
            } else if (SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY != null && SYS_SETTINGS.ORDER_ADDRESS_SHOW_CITY == 2) {
                address += "" + infoVO.getAddress();
                if (ValidateUtil.isNotNull(infoVO.getCounty())) {
                    address += " " + infoVO.getCounty();
                }
                if (ValidateUtil.isNotNull(infoVO.getCity())) {
                    address += " " + infoVO.getCity();
                }
                if (ValidateUtil.isNotNull(infoVO.getProvince())) {
                    address += " " + infoVO.getProvince();
                }
            } else {
                address += "" + infoVO.getAddress();
            }
//            sb.append("<B>").append(infoVO.getAddress()).append("</B>").append("<BR>");
            sb.append("<B>").append(address).append("</B>").append("<BR>");
        }
        sb.append("<B>").append(infoVO.getTelephone()).append("</B><BR>");
        sb.append("<B>").append(infoVO.getBuyer()).append("</B><BR>");
        if (SYS_SETTINGS.IS_PRINT_QR_CODE != null && SYS_SETTINGS.IS_PRINT_QR_CODE == 1) {
            sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        }
        return sb.toString();
    }


    // 易联云打
//    public static String get_E_LianYun_Content(String no, List<PrintOrderVO> printOrderVOList) {
//        if (!ValidateUtil.isAbsList(printOrderVOList)) {
//            return "";
//        }
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
//        StringBuffer sb = new StringBuffer();  //  封装信息
//        sb.append("<MN>").append(no).append("</MN>");   // 打印多联
//        sb.append("@@2点菜清单_订单编号: ").append(printOrderVOList.get(0).getOrderNo()).append("\r");
//        sb.append("店名: ").append(printOrderVOList.get(0).getShopName()).append("\r");
//        sb.append("联系人: ").append(printOrderVOList.get(0).getBuyer()).append("\r");
//        sb.append("电话: ").append(printOrderVOList.get(0).getUserTelephone()).append("\r");
//        sb.append("客户地址: ").append(printOrderVOList.get(0).getUserAddress()).append("\r");
//        sb.append("下单时间: ").append(simpleDateFormat.format(Long.valueOf(printOrderVOList.get(0).getCreatetime()))).append("\r");
//        sb.append("用餐地址: ").append(printOrderVOList.get(0).getShopName()).append("\r");
//        sb.append("商家电话: ").append(printOrderVOList.get(0).getShopTelephone()).append("\r");
//        sb.append("----------------------\r");
//        sb.append("@@2菜品明细").append("\r");
//
//        Double zongMoney = 0.0;
//        Double money = 0.0;
//        for (int i = 0; i < printOrderVOList.size(); i++) {
//            money = JYMathDoubleUtils.mul(printOrderVOList.get(i).getGoodsMoney(), printOrderVOList.get(i).getTotalcount());
//            zongMoney = JYMathDoubleUtils.add(zongMoney, money);   // 商品金额
//            String specs = "";
//            if (StringUtils.isNotEmpty(printOrderVOList.get(i).getSpecsName()) && !"null".equalsIgnoreCase(printOrderVOList.get(i).getSpecsName())) {
//                specs = " " + printOrderVOList.get(i).getSpecsName();
//            }
//            sb.append(i + 1).append(". ").append(printOrderVOList.get(i).getGoodsName()).append(specs).append("-").append(printOrderVOList.get(i).getGoodsMoney()).append("元*").append(printOrderVOList.get(i).getTotalcount()).append("份\r");
//
//            // 规格值
//            if (StringUtils.isNotEmpty(printOrderVOList.get(i).getGoodsAttrs()) && !"null".equalsIgnoreCase(printOrderVOList.get(i).getGoodsAttrs())) {
//                sb.append("  属性:").append(printOrderVOList.get(i).getGoodsAttrs()).append("\r");
//            }
//        }
//        sb.append("----------------------\r");
//        sb.append("@@2支付方式").append("\r");
//        zongMoney = JYMathDoubleUtils.add(zongMoney, printOrderVOList.get(0).getDeliveryPrice());           // 配送费
//        //  活动满减
//        sb.append("外送费用: ").append(printOrderVOList.get(0).getDeliveryPrice()).append("元").append("\r");
//        sb.append("菜品金额: ").append("总价").append(zongMoney).append("元-").append("活动满减").append(printOrderVOList.get(0).getOriginalYunFeiShop()).append("元-").append("配送满减").append(printOrderVOList.get(0).getAwardMoney()).append("元").append("\r");
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getAwardMoney());             //  配送满减
//        zongMoney = JYMathDoubleUtils.sub(zongMoney, printOrderVOList.get(0).getOriginalYunFeiShop());
//        sb.append("应付金额: ").append(zongMoney).append("元\r");
//        sb.append("留言: ").append(printOrderVOList.get(0).getNote()).append("\r");
//
//        String content = null;   //  urlencode
//        try {
//            content = URLEncoder.encode(sb.toString(), "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return content;
//    }


    public static String get_E_LianYun_Content_2(String no, OrderInfoVO infoVO) {
        if (infoVO == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        StringBuffer sb = new StringBuffer();  //  封装信息
        sb.append("<MN>").append(no).append("</MN>");   // 打印多联
        sb.append("<FS2>").append(infoVO.getPreDayNo()).append("</FS2>\r");
        if (infoVO.getIsAppointment() != null && infoVO.getIsAppointment() == 1) {
            sb.append("<center><FB>" + "预约单" + "</FB></center>\r");
        }
        sb.append("店    名: ").append(infoVO.getShopName()).append("\r");
        sb.append("商家电话: ").append(infoVO.getShopPhone()).append("\r");
        sb.append("订单编号:").append(infoVO.getOrderNo()).append("\r");
        if (SYS_SETTINGS.HAS_ORDER_SECOND_POSTMAN_VERIFY_CODE == 1 && ValidateUtil.isNotNull(infoVO.getVerifyCode())) {
            sb.append("提货码:").append(infoVO.getVerifyCode()).append("\r");
        }
        sb.append("姓    名:").append(infoVO.getBuyer()).append("\r");
        sb.append("联系电话:<FS>").append(infoVO.getTelephone()).append("</FS>\r");
        sb.append("订单时间:").append(simpleDateFormat.format(infoVO.getCreateTime())).append("\r");
        if (ValidateUtil.isNull(infoVO.getZiQuTime()) || ValidateUtil.isNotAbsLong(infoVO.getZiQuTime())) {
            sb.append("指定时间送达:").append("<FS>").append("立即送达").append("</FS>").append("\r");
        } else {
            sb.append("指定时间送达:").append("\r<FS>").append(simpleDateFormat.format(infoVO.getZiQuTime())).append("</FS>").append("\r");
        }
        List<OrderGoodsVO> goodsVOList = infoVO.getGoods();
        if (ValidateUtil.isAbsList(goodsVOList)) {
            sb.append("\r---------商品清单-----------\r");
            for (OrderGoodsVO g : goodsVOList) {
                // 规格
                String specs = "";
                if (StringUtils.isNotEmpty(g.getSpecs()) && !"null".equalsIgnoreCase(g.getSpecs())) {
                    specs = " " + g.getSpecs();
                }
                // 属性
                String goodsAttrVals = "";
                if (StringUtils.isNotEmpty(g.getGoodsAttrVals()) && !"null".equalsIgnoreCase(g.getGoodsAttrVals())) {
                    goodsAttrVals = "  属性:" + g.getGoodsAttrVals();
                }
                if (g.getIsZhekou() == null || g.getIsZhekou() == 0) {
                    sb.append("<FS>").append(g.getName()).append(specs).append("  ").append("￥").append(g.getGoodsPrice()).append(" ").append(" x").append(g.getTotalCount()).append(ValidateUtil.isNull(g.getGoodsAttrVals()) ? "" : g.getGoodsAttrVals()).append("</FS>").append("\r");
                } else {
                    sb.append("<FS>").append(g.getName()).append(specs).append("(折)").append("  ").append("￥").append(g.getGoodsPrice()).append(" ").append(" x").append(g.getTotalCount()).append(ValidateUtil.isNull(g.getGoodsAttrVals()) ? "" : g.getGoodsAttrVals()).append("</FS>").append("\r");
                }
                if (StringUtils.isNotEmpty(goodsAttrVals)) {
                    sb.append("<FH>").append("").append(goodsAttrVals).append("").append("</FH>").append("\r");
                }
            }
        }
        sb.append("\r");
        sb.append("\r");
        if (infoVO.getGameAward() != null && infoVO.getGameAward().size() > 0) {
            sb.append("-------优惠信息-----\r");
            if (infoVO.getGameAward().size() == 1) {
                sb.append(("优    惠：" + infoVO.getGameAward().get(0).getAward() + "\n"));
            } else {
                for (int i = 0; i < infoVO.getGameAward().size(); i++) {
                    sb.append(("优    惠：" + (i + 1) + infoVO.getGameAward().get(i).getAward() + "\n"));
                }
            }
        }

        sb.append("\r");

        if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
            String canju = "";//餐具
            String dabaofei = "";//打包费
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                if (null != infoVO.getCanJuPrice() && infoVO.getCanJuPrice() > 0) {
                    canju = "餐具：" + infoVO.getCanJuPrice() + "  x" + infoVO.getCanJuCount();
                } else {
                    canju = "餐具：" + "  x" + infoVO.getCanJuCount();
                }
            }
            if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
                dabaofei = "打包费：" + infoVO.getPacketPrice();
            }
            sb.append(canju).append("\r");
            sb.append(dabaofei).append("\r");
        } else {
            String canju = "";//餐具
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                if (null != infoVO.getCanJuPrice() && infoVO.getCanJuPrice() > 0) {
                    canju = "餐具：" + infoVO.getCanJuPrice() + "  x" + infoVO.getCanJuCount();
                } else {
                    canju = "餐具：" + "  x" + infoVO.getCanJuCount();
                }
            }
            sb.append(canju);
        }
        if (infoVO.getIsZiQu() != 1) {
            sb.append("运    费:").append(infoVO.getDeliveryPrice()).append("\r");
        }
        sb.append("优惠金额:").append(infoVO.getAwardMoney()).append("\r");
        sb.append("总计金额:").append(infoVO.getTotalPrice()).append("\r");
        sb.append("支付金额:").append(infoVO.getTotalPrice()).append("\r");
        if (ValidateUtil.isNotNull(infoVO.getPayType())) {
            if (infoVO.getPayType().contains("wx")) {
                sb.append("支付方式:").append("微信").append("\r");
            } else if (infoVO.getPayType().contains("alipay")) {
                sb.append("支付方式:").append("支付宝").append("\r");
            }
        }
        if (infoVO.getIsZiQu() == 1) {
            // 自取
            sb.append("方    式:<FS>").append("自    提").append("</FS>\r");
        } else {
            //配送
            sb.append("方    式:").append("<FS>配    送</FS>").append("\r");
            sb.append("地    址:").append("<FS>").append(infoVO.getAddress()).append("</FS>").append("\r");
        }
        sb.append("备    注:").append("<FW>").append(ValidateUtil.isNull(infoVO.getNote()) ? "" : infoVO.getNote()).append("</FW>").append("\r").append("\r");
        if (SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE != null && SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE == 1 && ValidateUtil.isNotNull(infoVO.getShopNote())) {
            sb.append("商家 备注:").append("<FW>").append(ValidateUtil.isNull(infoVO.getShopNote()) ? "" : infoVO.getShopNote()).append("</FW>").append("\r").append("\r");
        }
//        sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        if (SYS_SETTINGS.IS_PRINT_QR_CODE != null && SYS_SETTINGS.IS_PRINT_QR_CODE == 1) {
            sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        }
        String content = null;   //  urlencode
        try {
            content = URLEncoder.encode(sb.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return content;
    }


    public static String get_E_LianYun_content(String no, OrderInfoVO infoVO) {
        if (SYS_SETTINGS.PRINT_STYLE_TYPE != null && SYS_SETTINGS.PRINT_STYLE_TYPE == 2) {
            try {
                return get_E_LianYun_Content_3_M(no, infoVO);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return "";
            }
        } else {
            // 本系统的
            return get_E_LianYun_Content_2(no, infoVO);
        }
    }

    // 易联云
    private static String get_E_LianYun_Content_3_M(String no, OrderInfoVO infoVO) throws UnsupportedEncodingException {
        if (infoVO == null) {
            return "";
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        StringBuilder sb = new StringBuilder();
        sb.append("<MN>").append(no).append("</MN>");   // 打印多联
        if (infoVO.getIsAppointment() != null && infoVO.getIsAppointment() == 1) {
            sb.append("<center><FB>" + "预约单" + "</FB></center>\r");
        }
        sb.append("<center>****<FS2>  # " + infoVO.getPreDayNo() + "  </FS2>****</center>");
        sb.append("<center><FB>" + infoVO.getShopName() + "</FB></center>\r");
        sb.append("下单时间: " + simpleDateFormat.format(new Date())).append("\r");
        sb.append("<FB>********************************</FB>");
        sb.append("<FS2>备注:" + ((StringUtils.isEmpty(infoVO.getNote()) || infoVO.getNote().equalsIgnoreCase("null")) ? "" : infoVO.getNote()) + "</FS2>");
        sb.append("\r");
        if (SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE != null && SYS_SETTINGS.IS_HAS_PRINT_ORDER_SHOP_NOTE == 1 && ValidateUtil.isNotNull(infoVO.getShopNote())) {
            sb.append("<FS2>商家备注:" + ((StringUtils.isEmpty(infoVO.getShopNote()) || infoVO.getShopNote().equalsIgnoreCase("null")) ? "" : infoVO.getShopNote()) + "</FS2>");
            sb.append("\r");
        }
        sb.append("<FB>********************************</FB>");
        sb.append("--------- 商 品 清 单 ----------");
        List<OrderGoodsVO> goodsVOList = infoVO.getGoods();
        if (goodsVOList != null && !goodsVOList.isEmpty()) {
            for (OrderGoodsVO tempInfo : goodsVOList) {
                String tempStr = getGoodsRow(tempInfo);
                if (StringUtils.isNotEmpty(tempStr)) {
                    sb.append("<FH2>").append(tempStr).append("</FH2>");
                }
            }
        }
        sb.append("\r");
        // 商品结束
        sb.append("<FB>********************************</FB>");
        sb.append("--------- 其 他 信 息 ----------");
        sb.append("订单编号:").append(infoVO.getOrderNo()).append("\r");
        if (SYS_SETTINGS.HAS_ORDER_SECOND_POSTMAN_VERIFY_CODE == 1 && ValidateUtil.isNotNull(infoVO.getVerifyCode())) {
            sb.append("提货码:").append(infoVO.getVerifyCode()).append("\r");
        }
        sb.append("商家电话:").append(infoVO.getShopPhone()).append("\r");
        if (ValidateUtil.isNull(infoVO.getZiQuTime()) || ValidateUtil.isNotAbsLong(infoVO.getZiQuTime())) {
            sb.append("送达时间:").append("<FH>").append("立即送达").append("</FH>").append("\r");
        } else {
            sb.append("送达时间:").append("<FH>").append(simpleDateFormat.format(infoVO.getZiQuTime())).append("</FH>").append("\r");
        }

        if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                String temp = getOtherRow("餐具", infoVO.getCanJuPrice() == null ? null : infoVO.getCanJuPrice() + "", infoVO.getCanJuCount() + "", "");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
            if (null != infoVO.getPacketPrice() && infoVO.getPacketPrice() > 0) {
                String temp = getOtherRow("打 包 费", null, infoVO.getPacketPrice() + "", "￥");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
        } else {
            if (null != infoVO.getCanJuCount() && infoVO.getCanJuCount() > 0) {
                String temp = getOtherRow("餐具", infoVO.getCanJuPrice() == null ? null : infoVO.getCanJuPrice() + "", infoVO.getCanJuCount() + "", "");
                if (StringUtils.isNotEmpty(temp)) {
                    sb.append(temp);
                }
            }
        }
        String temp = "";
        // 运费
        if (infoVO.getIsZiQu() != 1) {
            temp = getOtherRow("运    费", null, infoVO.getDeliveryPrice() + "", null);
            if (StringUtils.isNotEmpty(temp)) {
                sb.append(temp);
            }
        }
        temp = getOtherRow("优惠金额", null, infoVO.getAwardMoney() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
        temp = getOtherRow("总计金额", null, infoVO.getTotalMoney() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
//        sb.append("优惠金额:").append(infoVO.getAwardMoney()).append("\r");
//        sb.append("总计金额:").append(infoVO.getTotalPrice()).append("\r");
        temp = getOtherRow("支付金额", null, infoVO.getTotalPrice() + "", null);
        if (StringUtils.isNotEmpty(temp)) {
            sb.append(temp);
        }
//        sb.append("支付金额:").append(infoVO.getTotalPrice()).append("\r");
        sb.append("--------- -------- ----------").append("\r");
        if (infoVO.getIsZiQu() == 1) {
            // 自取
            sb.append("方    式:<FB>").append("自    提").append("</FB>\r");
        } else {
            //配送
            sb.append("方    式:").append("<FB>配    送</FB>").append("\r");
            sb.append("<FS2>").append(infoVO.getAddress()).append("</FS2>").append("\r");
        }
        sb.append("<FS2>").append(infoVO.getTelephone()).append("</FS2>\r");
        sb.append("<FS2>").append(infoVO.getBuyer()).append("</FS2>\r");
        if (SYS_SETTINGS.IS_PRINT_QR_CODE != null && SYS_SETTINGS.IS_PRINT_QR_CODE == 1) {
            sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        }
//        sb.append("<QR>").append(infoVO.getOrderNo()).append("</QR>");
        String content = null;   //  urlencode
        try {
            content = URLEncoder.encode(sb.toString(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return content;
    }

    private static String getOtherRow(String name, String param2, String param3, String param3Mark) throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(param3)) {
            return "";
        }
        if (StringUtils.isEmpty(param3Mark)) {
            param3Mark = "";
        }
        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotEmpty(param2)) {
            if (param2.endsWith("0") && param2.indexOf(".") > 0) {
                param2 = param2.substring(0, param2.length() - 1);
            }
            if (param2.endsWith("0") && param2.indexOf(".") > 0) {
                param2 = param2.substring(0, param2.length() - 1);
            }
            if (param2.endsWith(".")) {
                param2 = param2.substring(0, param2.length() - 1);
            }
        } else {
            param2 = "";
        }
        if (param3.endsWith("0") && param3.indexOf(".") > 0) {
            param3 = param3.substring(0, param3.length() - 1);
        }
        if (param3.endsWith("0") && param3.indexOf(".") > 0) {
            param3 = param3.substring(0, param3.length() - 1);
        }
        if (param3.endsWith(".")) {
            param3 = param3.substring(0, param3.length() - 1);
        }
        int len1 = param2.getBytes("GBK").length;
        int len2 = param3.getBytes("GBK").length;
        int len3 = param3Mark.getBytes("GBK").length;
        String sf = "";
        if (StringUtils.isNotEmpty(param2)) {
            if (len1 > 6 - 1) {
                sf = "￥" + param2;
            } else {
                sf = "￥";
                sf += param2;
                for (int index = 0; index < 5 - len1; index++) {
                    sf += " ";
                }
            }
        } else {
            sf += "      ";
        }
        // count
        if (len2 > 4) {
            sf += param3Mark;
            sf += param3;
        } else {
            for (int index = 0; index < 4 - len2 - len3; index++) {
                sf += " ";
            }
            sf += param3Mark;
            sf += param3;
        }

        sb.append(name);
        for (int index = 0; index < 32 - sf.getBytes("GBK").length - name.getBytes("GBK").length; index++) {
            sb.append(" ");
        }
        sb.append(sf);
        return sb.toString();
    }

    private static String getGoodsRow(OrderGoodsVO orderGoodsVO) throws UnsupportedEncodingException {
        String specs = "";
        if (StringUtils.isNotEmpty(orderGoodsVO.getSpecs()) && !"null".equalsIgnoreCase(orderGoodsVO.getSpecs())) {
            specs = "[" + orderGoodsVO.getSpecs() + "]";
        }
        // 属性
        String goodsAttrVals = "";
        if (StringUtils.isNotEmpty(orderGoodsVO.getGoodsAttrVals()) && !"null".equalsIgnoreCase(orderGoodsVO.getGoodsAttrVals())) {
            goodsAttrVals = "(" + orderGoodsVO.getGoodsAttrVals() + ")";
        }
        String zhekou = "";
        if (orderGoodsVO.getIsZhekou() == null || orderGoodsVO.getIsZhekou() == 0) {
            zhekou = "";
        } else {
            zhekou = "(折)";
        }

        StringBuilder sb = new StringBuilder();
        String sf = "";
        String temp = "";
        temp = orderGoodsVO.getTotalCount() + "";
        int tempLength = temp.getBytes("GBK").length;
        if (tempLength >= 4) {
            sf += "*" + temp;
        } else {
            sf += "*";
            for (int i = 0; i < 4 - tempLength - 1; i++) {
                sf += " ";
            }
            sf += temp;
        }
        // 钱
        temp = orderGoodsVO.getGoodsPrice() + "";
        if (temp.trim().endsWith("0")) {
            temp = temp.substring(0, temp.length() - 1);
        }
        if (temp.trim().endsWith("0")) {
            temp = temp.substring(0, temp.length() - 1);
        }
        if (temp.trim().endsWith(".")) {
            temp = temp.substring(0, temp.length() - 1);
        }
        tempLength = temp.getBytes("GBK").length;
        if (tempLength > 6) {
            sf += temp;
        } else {
            for (int i = 0; i < 6 - tempLength; i++) {
                sf += " ";
            }
            sf += temp;
        }
        sf = "  " + sf;
        temp = orderGoodsVO.getName() + specs + goodsAttrVals + zhekou;
        if (32 - sf.getBytes("GBK").length - temp.getBytes("GBK").length >= 0) {
            sb.append(temp);
            int len1 = sf.getBytes("GBK").length;
            int len2 = temp.getBytes("GBK").length;
            for (int index = 0; index < 32 - len1 - len2; index++) {
                sb.append(" ");
            }
            sb.append(sf);
        } else {
            if (temp.getBytes("GBK").length % 32 == 0) {
                sb.append(temp);
            } else {
                sb.append(temp).append("\r");
            }
            for (int index = 0; index < 32 - sf.getBytes("GBK").length; index++) {
                sb.append(" ");
            }
            sb.append(sf);
        }
        return sb.toString();
    }

    private static String getGoodsRow_FE(OrderGoodsVO orderGoodsVO) throws Exception {
        String specs = "";
        if (StringUtils.isNotEmpty(orderGoodsVO.getSpecs()) && !"null".equalsIgnoreCase(orderGoodsVO.getSpecs())) {
            specs = "[" + orderGoodsVO.getSpecs() + "]";
        }
        // 属性
        String goodsAttrVals = "";
        if (StringUtils.isNotEmpty(orderGoodsVO.getGoodsAttrVals()) && !"null".equalsIgnoreCase(orderGoodsVO.getGoodsAttrVals())) {
            goodsAttrVals = "(" + orderGoodsVO.getGoodsAttrVals() + ")";
        }
        String zhekou = "";
        if (orderGoodsVO.getIsZhekou() == null || orderGoodsVO.getIsZhekou() == 0) {
            zhekou = "";
        } else {
            zhekou = "(折)";
        }

        String num = addSpace("* " + orderGoodsVO.getTotalCount(), 3);
        String total = addSpace(orderGoodsVO.getGoodsPrice() + "", 6);
        String otherStr = "  " + num + "  " + total;

        String title = orderGoodsVO.getName() + specs + goodsAttrVals + zhekou;
        int b1 = 18;
        int tl = title.getBytes("GBK").length;
        int spaceNum = (tl / b1 + 1) * b1 - tl;
        if (tl < b1) {
            for (int k = 0; k < spaceNum; k++) {
                title += " ";
            }
            title += otherStr;
        } else if (tl == b1) {
            title += otherStr;
        } else {
            List<String> list = null;
            if (isEn(title)) {
                list = getStrList(title, b1);
            } else {
                list = getStrList(title, b1 / 2);
            }
            String s0 = titleAddSpace(list.get(0));
            title = s0 + "" + otherStr + "<BR>";
            ;// 添加 单价 数量 总额
            String s = "";
            for (int k = 1; k < list.size(); k++) {
                s += list.get(k);
            }
            s = getStringByEnter(b1, s);
            title += s;
        }
        return title;
    }

    public static String print_message_(String orderNo, Long shopId, boolean sureBySystem) {
        if (ValidateUtil.isNull(orderNo)) {
            return AjaxResult.errorResult("订单号不能为空");
        }
        List<String> orderList = new ArrayList<>();
        orderList.add(orderNo);
        return print_message_(orderList, shopId, sureBySystem);
    }

    // 打印信息
    public static String print_message_(List<String> orderNoList, Long shopId, boolean sureBySystem) {
        if (ValidateUtil.isNotID(shopId)) {
            return AjaxResult.errorResult("店铺id不能为空");
        }
        if (orderNoList == null || orderNoList.isEmpty()) {
            return AjaxResult.errorResult("订单号不能为空");
        }
        List<PrintMessage> printMessageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, null);

        if (!ValidateUtil.isAbsList(printMessageList)) {
            return AjaxResult.errorResult("您还没有绑定可用的打印机");
        }
        List<PrintMessage> list = new ArrayList<>();
        // 只要是开启的都会打印
        for (PrintMessage message : printMessageList) {
            if (message == null) {
                continue;
            }
            if (message.getIsOpen() != null && message.getIsOpen() == 1) {
                list.add(message);
            }
        }
        if (!ValidateUtil.isAbsList(list)) {
            return AjaxResult.errorResult("请选择打印机");
        }
        boolean isConF_E = false;
        boolean isConE_Y = false;
        List<PrintMessage> printMessageList1 = new ArrayList<>();
        for (PrintMessage printMessage : list) {
            if (printMessage.getType() != null) {
                printMessageList1.add(printMessage);
                if (printMessage.getType() == PRINT_TYPE.PRINT_TYPE_FE) {
                    isConF_E = true;
                } else if (printMessage.getType() == PRINT_TYPE.PRINT_TYPE_EYUNLIAN) {
                    isConE_Y = true;
                }
            }
        }
        boolean flag = true;
        for (String orderNo : orderNoList) {
            OrderInfoVO infoVO = getPrintOrderInfoVo(orderNo);
            if (infoVO == null) {
                return AjaxResult.errorResult("订单信息不存在");
            }
            String content1 = "";
            String content2 = "";
            if (isConF_E) {
                String sysAppKey = SysCustomerCache.getInstance().getDefaultKey();
                SysCustomerInfo customerInfo = SysCustomerCache.getInstance().getInfo(sysAppKey);
                try {
                    content2 = PrintMan.get_F_E_Content(infoVO, customerInfo.getName(), sureBySystem);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (ValidateUtil.isAbsList(printMessageList1)) {
                for (PrintMessage p : printMessageList1) {
                    if (p.getType() == PRINT_TYPE.PRINT_TYPE_EYUNLIAN) {
                        int time = 1;
                        if (ValidateUtil.isAbsInteger(p.getFeTime()) && p.getFeTime() > 0) {
                            time = p.getFeTime();
                        }
                        content1 = PrintMan.get_E_LianYun_content(time + "", infoVO);
//                    content1 = PrintMan.get_E_LianYun_Content_2(time + "", infoVO); // 打印一次
                        flag = sendEYunLianContent(content1, p.getPartner(), p.getMachine_code(), p.getApikey(), p.getMkey());
                    } else if (p.getType() == PRINT_TYPE.PRINT_TYPE_FE) {
                        flag = PrintMan.sendFeContent(content2, p.getFeUser(), p.getFeUkey(), p.getMachine_code(), p.getFeTime());
                    }
                }
            }
        }
        //  调用打印
        if (!flag) {
            return AjaxResult.errorResult("打印失败,检查打印机");
        }
        return AjaxResult.successResult("打印成功!");
    }

    // 飞鹅生成签名字符串
    private static String signature(String USER, String UKEY, String STIME) {
        String s = DigestUtils.sha1Hex(USER + UKEY + STIME);
        return s;
    }

    // 易云联打印 签名获取
    private static String signRequest(Map<String, String> params, String apiKey, String mKey) {
        Map<String, String> sortedParams = new TreeMap<String, String>();
        sortedParams.putAll(params);
        Set<Map.Entry<String, String>> paramSet = sortedParams.entrySet();
        StringBuilder query = new StringBuilder();
        query.append(apiKey);
        for (Map.Entry<String, String> param : paramSet) {
            query.append(param.getKey());
            query.append(param.getValue());
        }
        query.append(mKey);
        String encryptStr = MD5Util.MD5Encode(query.toString(), "UTF-8").toUpperCase();
        return encryptStr;
    }

    // 查看飞鹅打印机再本地是不是有存储
    public static boolean machine_codeInShop(Long shopId, String machine_code) {
        if (shopId == null || StringUtils.isEmpty(machine_code)) {
            return false;
        }
        List<PrintMessage> messageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(shopId, PRINT_TYPE.PRINT_TYPE_FE);
        if (!ValidateUtil.isAbsList(messageList)) {
            return false;
        } else {
            for (PrintMessage p : messageList) {
                if (p != null && StringUtils.isNotEmpty(p.getMachine_code()) && machine_code.equalsIgnoreCase(p.getMachine_code())) {
                    return true;
                }
            }
        }
        return false;
    }

    //本地数据插入
    public static String insertshop(ShopInfo shopInfo, Long shopId, String machine_code, String name, String mkey, Integer pTime, String createUser, PrintConfig infoConfig) {
        long cTime = DateUtils.getCurrTime();
        PrintMessage p = new PrintMessage();
        p.setName(ValidateUtil.isNull(name) ? shopInfo.getShopName() : name);
        p.setCreateUser(createUser);
        p.setId(null);
        p.setDelFlag(0);
        p.setShopId(shopId);
        p.setCreateTime(cTime);
        p.setFeTime(pTime);
        p.setFeUkey(infoConfig.getFeUKey());
        p.setFeUser(infoConfig.getFeUser());
        p.setType(PRINT_TYPE.PRINT_TYPE_FE);
        p.setMachine_code(machine_code);
        p.setMkey(mkey);
        try {
            UserDaoSql.getInstance().insertObj(PojoTables.PRINT_MESSAGE, p);
        } catch (Exception e) {
            e.printStackTrace();
            PrintMan.send_fei_e_print_unbind(infoConfig.getFeUser(), infoConfig.getFeUKey(), machine_code);
            return AjaxResult.errorResult("添加失败");
        }
        PrintMessageMemory.getInstance().add(cTime);
        return AjaxResult.successResult();
    }

    // todo : 获取订单详情
    private static OrderInfoVO getPrintOrderInfoVo(String orderNo) {
        OrderInfoVO infoVO = OrderMan.getOrderDetail(orderNo);
        if (infoVO == null) {
            return null;
        }
        List<OrderGoodsVO> list = new ArrayList<>();
        List<OrderGoodsVO> orderGoodsVOList = infoVO.getGoods();
        if (ValidateUtil.isAbsList(orderGoodsVOList)) {
            for (OrderGoodsVO vo : orderGoodsVOList) {
                if (vo == null) {
                    continue;
                }
                if (vo.getTotalCount() <= vo.getBackTotalCount()) {
                    continue;
                }
                vo.setTotalCount(vo.getTotalCount() - vo.getBackTotalCount());
                if (ValidateUtil.isNotID(vo.getCategoryId())) {
                    vo.setCategoryId(0L);
                }
                list.add(vo);
            }
        }
        Collections.sort(list, Comparator.comparingLong(OrderGoodsVO::getCategoryId));
        infoVO.setGoods(list);
        return infoVO;
    }

//    public static void main(String[] args) {
//
//        String s = send_fei_e_print_bind("yangtongkuan@qq.com", "kngEEY64n7HFNGN2", "930500103#3u7m2wsp");
//        JSONObject jsonObject = JSONObject.fromObject(s);
//        if (jsonObject.containsKey("ret") && jsonObject.getString("ret").equals("0")) {
//            String data = jsonObject.getString("data");
//
//        }
//    }


    public static String addSpace(String str, int size) {
        int len = str.length();
        if (len < size) {
            for (int i = 0; i < size - len; i++) {
                str += " ";
            }
        }
        return str;
    }

    public static Boolean isEn(String str) {
        Boolean b = false;
        try {
            b = str.getBytes("GBK").length == str.length();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return b;
    }

    public static List<String> getStrList(String inputString, int length) {
        int size = inputString.length() / length;
        if (inputString.length() % length != 0) {
            size += 1;
        }
        return getStrList(inputString, length, size);
    }

    public static List<String> getStrList(String inputString, int length, int size) {
        List<String> list = new ArrayList<String>();
        for (int index = 0; index < size; index++) {
            String childStr = substring(inputString, index * length, (index + 1) * length);
            list.add(childStr);
        }
        return list;
    }

    public static String substring(String str, int f, int t) {
        if (f > str.length())
            return null;
        if (t > str.length()) {
            return str.substring(f, str.length());
        } else {
            return str.substring(f, t);
        }
    }

    public static String titleAddSpace(String str) {
        int k = 0;
        int b = 18;
        try {
            k = str.getBytes("GBK").length;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        for (int i = 0; i < b - k; i++) {
            str += " ";
        }
        return str;
    }

    public static String getStringByEnter(int length, String string) throws Exception {
        for (int i = 1; i <= string.length(); i++) {
            if (string.substring(0, i).getBytes("GBK").length > length) {
                return string.substring(0, i - 1) + "<BR>" + getStringByEnter(length, string.substring(i - 1));
            }
        }
        return string;
    }

    /**
     * 飞鹅打印机 语音播报
     *
     * @param orderInfo
     */
    public static void sendApplyCancelOrderVoice(OrderInfo orderInfo) {
        if (ValidateUtil.isNotNull(SYS_SETTINGS.PRINT_CANCEL_ORDER_APPLY_INSTRUCTION)
                && orderInfo != null && orderInfo.getOrderType() != null
                && orderInfo.getOrderType() - ORDER_TYPE.SHOP_GOODS == 0
                && ValidateUtil.isID(orderInfo.getShopId())) {

            List<PrintMessage> printMessageList = PrintMessageMemory.getInstance().listPrintMessageOfShopId(orderInfo.getShopId(), PRINT_TYPE.PRINT_TYPE_FE);

            if (!ValidateUtil.isAbsList(printMessageList)) {
                return;
            }
            printMessageList = printMessageList.stream().filter(item -> item.getIsOpen() != null && item.getIsOpen() == 1).collect(Collectors.toList());
            if (!ValidateUtil.isAbsList(printMessageList)) {
                return;
            }
            String content = SYS_SETTINGS.PRINT_CANCEL_ORDER_APPLY_INSTRUCTION;
            for (PrintMessage p : printMessageList) {
                System.out.println("飞鹅语音申请退款语音播报：orderNo:" + orderInfo.getOrderNo() + ":" + PrintMan.sendFeContent(content, p.getFeUser(), p.getFeUkey(), p.getMachine_code(), 1));
            }
        }
    }

}
